﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windows.Foundation.Collections;

namespace LocalSettings
{
    public class BaseSettingsStorage
    {
        protected static T GetPropertyResultFrom<T>(string name, T defaultValue, IPropertySet properties)
        {
            try
            {
                object settingObj;
                if (properties.TryGetValue(name, out settingObj))
                {
                    var result = (T)settingObj;
                    return result;
                }
            }
            catch (Exception)
            {
            }

            return defaultValue;
        }

        protected static T GetPropertyResult<T>(string name, T defaultValue)
        {
            return GetPropertyResultFrom(name, defaultValue, Windows.Storage.ApplicationData.Current.LocalSettings.Values);
        }

        protected static bool IsPropertyValueExist(string name)
        {
            var exist = false;
            try
            {
                var settingObj = Windows.Storage.ApplicationData.Current.LocalSettings.Values[name];
                exist = settingObj != null;
            }
            catch (Exception)
            {
            }

            return exist;
        }

        protected static void SetPropertyResultTo(string name, object value, IPropertySet properties)
        {
            properties[name] = value;
        }

        protected static void SetPropertyResult(string name, object value)
        {
            SetPropertyResultTo(name, value, Windows.Storage.ApplicationData.Current.LocalSettings.Values);
        }

        protected static void SaveChain<T>(String name, IEnumerable<T> collection, Func<T, String> selector = null)
        {
            if (collection == null || collection.Count() == 0)
            {
                SetPropertyResult(name, "");
                return;
            }
            if (selector == null)
            {
                selector = x => x.ToString();
            }

            var res = String.Join("|", collection.Select(selector));
            SetPropertyResult(name, res);
        }

        protected static List<T> LoadChain<T>(String name, Func<String, T> parser)
        {
            var resultCollection = new List<T>();
            var loadedString = GetPropertyResult(name, "");

            if (String.IsNullOrEmpty(loadedString))
            {
                return resultCollection;
            }

            return loadedString.Split('|').Select(parser).ToList();
        }
    }
}
